package view;

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

import xl.Address;
import xl.Adjustment;
import xl.NumberAdjustment;
import model.*;

public class SheetView extends JPanel implements Observer {
    private static Adjustment adjustment = new NumberAdjustment(14, 2);
    private SlotView slotView[][];
    private int rows, cols;
    private Sheet sheet;

    public SheetView(int rows, int cols, Sheet sheet, CurrentView currentView, Editor editor) {
        this.rows = rows;
        this.cols = cols;
        slotView = new SlotView[rows][cols];
        setLayout(new GridLayout(rows + 1, cols, 2, 2));
        for (int j = 0; j < cols; j++) {
            JLabel lbl = new JLabel(String.valueOf((char) (j + 'A')),
                    SwingConstants.CENTER);
            lbl.setBackground(Color.LIGHT_GRAY);
            lbl.setOpaque(true);
            add(lbl);
        }
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                SlotView slotViewIj = new SlotView(currentView, new Address(i,j), slotView, editor, sheet);
                add(slotViewIj);
                slotView[i][j] = slotViewIj;
            }
        }
        slotView[0][0].setBackground(Color.PINK);
        setBackground(Color.BLACK); 
        this.sheet = sheet;
        sheet.addObserver(this);
    }

	
	public void update(Observable o, Object arg) {			
			for (int i = 0; i < rows; i++) {
	            for (int j = 0; j < cols; j++) {
	                SlotView slotViewij = slotView[i][j];
	                Address address = new Address(i,j);	                
	                Cell cell = sheet.getSheet().get(address);
	                String s = "";
	                if(cell != null){	                	
	                	if(cell instanceof CommentCell){
	                		s = cell.toString();
	                		slotViewij.setHorizontalAlignment(SwingConstants.LEFT);
	                	}else{
	                		double value = cell.getValue(sheet);
	                		s = Double.toString(value);
	                }  
	            }
	                slotViewij.setText(s);
	        }
			}
		
	}
}
